package public

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func GetIndexProduct(c *gin.Context) {
	rdb := redis.NewClient(&redis.Options{
		Addr:     "114.132.235.219:6379",
		Password: "lzt123456.",
		DB:       1,
	})

	productNormal, err := rdb.Keys(ctx, "product:normal:*").Result()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"err": 1,
			"msg": "Redis 获取 productNormal 失败",
		})
		return
	}

	productSpike, err := rdb.Keys(ctx, "product:spike:*").Result()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"err": 1,
			"msg": "Redis 获取 productSpike 失败",
		})
		return
	}

	var productListNormal []map[string]string
	var productListSpike []map[string]string

	for _, key := range productNormal {
		product, err := rdb.HGetAll(ctx, key).Result()
		if err != nil {
			continue // 忽略错误项
		}
		productListNormal = append(productListNormal, product)
	}

	for _, key := range productSpike {
		product, err := rdb.HGetAll(ctx, key).Result()
		if err != nil {
			continue // 忽略错误项
		}
		productListSpike = append(productListSpike, product)
	}

	productListAll := map[string]interface{}{
		"normal": productListNormal,
		"spike":  productListSpike,
	}

	c.JSON(http.StatusOK, gin.H{
		"err":         0,
		"msg":         "获取成功",
		"productList": productListAll,
	})
}
